package com.gensdai.leliang.Preferences;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.preference.SwitchPreference;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;

import com.gensdai.leliang.AppApplication;
import com.gensdai.leliang.R;
import com.gensdai.leliang.activity.OrderInfoActivity;
import com.gensdai.leliang.utils.PreferencesUtils;
import com.gensdai.leliang.view.Toaster;

import java.util.List;

/**
 * Created by zsxx on 2017/9/13.
 */

public class PreferencesActivity extends PreferenceActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // setContentView(R.layout.activity_main);
        //show = (TextView) findViewById(R.id.show);
    }


    @Override
    public void onBuildHeaders(List<Header> target) {
        loadHeadersFromResource(R.xml.settingprefrence, target);//加载列表布局就跟前面选项菜单加载无异

    }

    @Override
    protected boolean isValidFragment(String fragmentName) {//fragmentName有效
        return true;
    }

    public static class prefer1 extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener, Preference.OnPreferenceChangeListener {//Preferencesfragment负责加载参数设置布局文件

        public static final String CURRENTPREFRE = "prefren";
        public static final String CURRENTPREFRE_PIC = "prefren_pic";

        public static final String DEFAULTURL = "http://139.196.200.97:8000/lelongApp/";
        public static final String DEFAULTPICURL = "http://139.196.200.97:8000/";

        private EditTextPreference url;
        private EditTextPreference picurl;
        private PreferenceCategory pfc;
        private Preference restartApp;

        private CheckBoxPreference serviceTest;
        private CheckBoxPreference serviceRuibo;
        private CheckBoxPreference serviceLujianan;
        private CheckBoxPreference serviceGuoXiao;

        private SwitchPreference lastSwitch;
        private SwitchPreference afterSwitch;
        SharedPreferences settings;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.pres1);
            settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
            url = (EditTextPreference) getPreferenceScreen().findPreference("edittext_custom_url");
            picurl = (EditTextPreference) getPreferenceScreen().findPreference("edittext_custom_pic_url");
            pfc = (PreferenceCategory) getPreferenceScreen().findPreference("current_key");
            restartApp = (Preference) getPreferenceScreen().findPreference("restartApp");


            restartApp.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    AlertDialog alertDialog;
                    final AlertDialog.Builder normalDialog =
                            new AlertDialog.Builder(getActivity());
                    normalDialog.setMessage("重启APP吗？");
                    normalDialog.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //重启app代码
                            Intent intent = getActivity().getBaseContext().getPackageManager()
                                    .getLaunchIntentForPackage(getActivity().getBaseContext().getPackageName());
                            PendingIntent restartIntent = PendingIntent.getActivity(getActivity().getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
                            AlarmManager mgr = (AlarmManager)getActivity().getSystemService(Context.ALARM_SERVICE);
                            mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent); // 1秒钟后重启应用
                            System.exit(0);
                            dialog.dismiss();
                        }
                    });
                    normalDialog.setNegativeButton("点错了", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });

                    normalDialog.setCancelable(false);
                    // 显示
                    alertDialog = normalDialog.create();
                    alertDialog.show();
                    return true;
                }
            });

            serviceTest = (CheckBoxPreference) getPreferenceScreen().findPreference("service_test");
            serviceRuibo = (CheckBoxPreference) getPreferenceScreen().findPreference("service_ruibo");
            serviceLujianan = (CheckBoxPreference) getPreferenceScreen().findPreference("service_lujianan");
            serviceGuoXiao = (CheckBoxPreference) getPreferenceScreen().findPreference("service_guoxiao");

            serviceTest.setOnPreferenceChangeListener(this);
            serviceRuibo.setOnPreferenceChangeListener(this);
            serviceLujianan.setOnPreferenceChangeListener(this);
            serviceGuoXiao.setOnPreferenceChangeListener(this);

            afterSwitch = (SwitchPreference) getPreferenceScreen().findPreference("after_checkbox_preference");
            lastSwitch = (SwitchPreference) getPreferenceScreen().findPreference("last_checkbox_preference");
            lastSwitch.setOnPreferenceChangeListener(this);
            afterSwitch.setOnPreferenceChangeListener(this);


        }

        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            if (key.equals("edittext_custom_url")) {
                InitTextSummary();
            }
            if (key.equals("edittext_custom_pic_url")) {
                InitTextSummary();
            }
        }

        @Override
        public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {


            InitTextSummary();

            return super.onPreferenceTreeClick(preferenceScreen, preference);
        }

        public void InitTextSummary() {
            String currentUrl = DEFAULTURL;
            String currentPicUrl = DEFAULTPICURL;
            if (url == null) {
                return;
            }

            if (afterSwitch.isChecked()) {
                currentUrl = checkyuset();
            } else if (lastSwitch.isChecked()) {
                if (TextUtils.isEmpty(url.getText())) {
                    url.setSummary("请输入接口地址，例如 http://demo.dotnetcms.org/worklog/");
                } else {
                    String txt = settings.getString("edittext_custom_url", "xxx");
                    url.setSummary("当前地址：" + txt);
                    currentUrl = txt;
                }
            }
            if (TextUtils.isEmpty(url.getText())) {
                url.setSummary("请输入接口地址，例如 http://demo.dotnetcms.org/worklog/");
            } else {
                String txt = settings.getString("edittext_custom_url", "xxx");
                url.setSummary("当前地址：" + txt);
            }

            if (TextUtils.isEmpty(picurl.getText())) {
                picurl.setSummary("请输入图片接口地址，例如 http://139.196.200.97:8000/");
            } else {
                String txt = settings.getString("edittext_custom_pic_url", "http://139.196.200.97:8000/");
                picurl.setSummary("当前地址：" + txt);
                currentPicUrl = txt;
            }


            pfc.setTitle("当前地址：" + currentUrl);
            PreferencesUtils.setStringPreferences(getActivity(), AppApplication.PREFERENCE_NAME,CURRENTPREFRE,currentUrl);
            PreferencesUtils.setStringPreferences(getActivity(), AppApplication.PREFERENCE_NAME,CURRENTPREFRE_PIC,currentPicUrl);
        }

        @Override
        public void onResume() {
            super.onResume();

            InitTextSummary();
            getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
        }

        @Override
        public void onPause() {
            getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
            super.onPause();
        }

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            final String key = preference.getKey();
            if ("after_checkbox_preference".equals(key)) {
                if ((Boolean) newValue) {
                    lastSwitch.setChecked(false);
                }
            }
            if ("last_checkbox_preference".equals(key)) {
                if ((Boolean) newValue) {
                    afterSwitch.setChecked(false);
                }
            }


            switch (key) {
                case "service_test":
                    if ((Boolean) newValue) {
                        serviceRuibo.setChecked(false);
                        serviceLujianan.setChecked(false);
                        serviceGuoXiao.setChecked(false);
                    }
                    break;
                case "service_ruibo":
                    if ((Boolean) newValue) {
                        serviceTest.setChecked(false);
                        serviceLujianan.setChecked(false);
                        serviceGuoXiao.setChecked(false);
                    }
                    break;
                case "service_lujianan":
                    if ((Boolean) newValue) {
                        serviceRuibo.setChecked(false);
                        serviceTest.setChecked(false);
                        serviceGuoXiao.setChecked(false);
                    }
                    break;
                case "service_guoxiao":
                    if ((Boolean) newValue) {
                        serviceRuibo.setChecked(false);
                        serviceLujianan.setChecked(false);
                        serviceTest.setChecked(false);
                    }
                    break;
                default:
                    break;
            }

            return true;
        }

         String checkyuset() {
            String currentUrl = "";
            if (serviceTest.isChecked()) {

                currentUrl = DEFAULTURL;

            } else if (serviceRuibo.isChecked()) {

                currentUrl = "http://192.168.1.130:8080/lelongV1/lelongApp/";

            } else if (serviceLujianan.isChecked()) {

                currentUrl = "http://192.168.1.28:8080/lelongApp/";

            } else if (serviceGuoXiao.isChecked()) {

                currentUrl = "http://192.168.1.89:8080/lelong/lelongApp/";

            } else {
                currentUrl = DEFAULTURL;
            }

            return currentUrl;
        }
    }
}